<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
    #fileimg{
        width: 200px;
        height: 200px;
        border: 1px solid #eee;
    }
    .Btn{
        width: 100px;
        background: #4BCD61;
        border: 0px;
    }
    </style>
</head>
<body>
    <form  enctype="multipart/form-data" id="form1">
        <input type="file" id="file" name="filename" onchange="upCh(this)"/>
        <br/>
        <img id="fileimg" src="" />
        <br/>
        <button class="Btn" onclick="fileClick()">上传图片</button>
    </form>

    <script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
    <script>
            function fileClick() {
                //todo;
                let file = $('#file')[0].files[0];
                let isJPG = file.type === "image/jpeg";
                if (!isJPG){
                    alert("上传的不是jpg格式");
                    return;
                }
                let formData = new FormData($("#form1")[0]);
                formData.append("filename",file);
                $.ajax({
                    url: "upImg",
                    method: "post",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(data) {
                        if(data.status != 1) {
                            alert(data.message);
                            location.assign("test2.html");
                        }else{
                            alert(data.message);
                        }
                    },
                    error: function(){
                        alert("出现异常")
                    }
                })
            }

            function upCh(file) {
                let img = document.getElementById('fileimg');
                let formData = new FormData();
                let imgUrl = file.files[0];
                console.log(imgUrl);
                if (imgUrl) {
                    console.log(1);
                    formData.append('file',imgUrl);
                    img.src = window.URL.createObjectURL(imgUrl);
                }
            }
        </script>
</body>
</html>